﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Tanmia.Basis.Security;
using Tanmia.Basis;
using System.Threading;
using System.Security.Principal;

namespace Tanmia.Basis.Security.Adapter
{
    public class DatabaseAuthenticationService : IAuthenticationService
    {
        private ISession session;
        public DatabaseAuthenticationService(ISession session)
        {
            this.session = session;
        }

        #region IAuthenticationService Members

        public ApplicationUserInfo User { get; private set; }

        public bool Authenticate(ApplicationUserInfo userInfo)
        {
            ICriteria criteria = session.CreateCriteria<UserAdapter>();
            criteria.Add(Expression.Eq("Username", userInfo.Username));
            criteria.Add(Expression.Eq("Password", userInfo.Password));
            UserAdapter tuser = criteria.UniqueResult<UserAdapter>();
            if (tuser != null)
            {
                User = tuser;
                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(User.Username, "Database"), null);
                return true;
            }

            return false;
        }

        #endregion
    }
}
